package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.bcorder.service.SalesPlanService;
import com.epoch.app.otsapplicationappsdk.monthplanshow.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.monthplanshow.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.monthplanshow.service.MonthPlanShowService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.List;

@Service
public class MonthPlanShowV2ServiceImpl implements MonthPlanShowService {

    private static final Log log = Log.getLogger(MonthPlanShowV2ServiceImpl.class);

    @Autowired
    SalesPlanService salesPlanService;

//    @Autowired
//    BcOtsService bcOtsService;
    @Autowired
    BcOrderService bcOtsService;

    @Override
    @FacadeInvoker
    public Object render(RenderRequest renderRequest) {
        Object requestBody = renderRequest.getRequestBody();
        if (requestBody == null) {
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(requestBody));
            String planId = jsonObject.getString("planId");
            if (StringUtils.isBlank(planId)) {
                throw new Exception("缺失必要参数:planId");
            }
            Integer pageSize = jsonObject.getInteger("pageSize") == null ? 10 : jsonObject.getInteger("pageSize");
            Integer currentPage = jsonObject.getInteger("currentPage") == null ? 1 : jsonObject.getInteger("currentPage");

            handle(result, planId, pageSize, currentPage);
            result.put("planId", planId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    private void handle(JSONObject result, String planId, Integer pageSize, Integer currentPage) throws Exception {
        //查询月度计划标题
        QuerySalePlanInfoRequest planParam = new QuerySalePlanInfoRequest();
        planParam.setId(planId);
        QuerySalePlanInfoResponse planInfoResponse = salesPlanService.querySalePlanInfo(planParam);
        boolean isPublished = false;
        if (planInfoResponse != null && planInfoResponse.getResult() != null) {
            String formatPlanTime = planInfoResponse.getResult().getFormatPlanTime();
            if (StringUtils.isNotBlank(formatPlanTime)) {
                result.put("title", formatPlanTime + "-月度计划");
            }
            Integer status = planInfoResponse.getResult().getStatus();
            if (status != null) {
                isPublished = status > 3;
            }
        }
        result.put("isPublished", isPublished);
        //查询小计
        try {
            SubTotalSalesPlanSCItemRequest subTotalSalesPlanSCItemRequest = SubTotalSalesPlanSCItemRequest
                    .builder()
                    .planId(planId)
                    .poolType(StatPoolTypeEnum.ORGANIZATION.getPoolType())
                    .build();
            SubTotalSalesPlanSCItemResponse planSCItemResponse = salesPlanService.subTotalSalesPlanSCItem(subTotalSalesPlanSCItemRequest);
            if (planSCItemResponse != null) {
                result.put("subTotal", planSCItemResponse.getResult());
            }
        }catch (Exception e){
            log.error("查询月度计划货品小计异常{}", e);
        }
        //查询明细列表
        PageQueryPlanScItemListRequest request = PageQueryPlanScItemListRequest
                .builder()
                .planId(planId)
                .poolType(StatPoolTypeEnum.SC_ITEM.getPoolType())
                .page(currentPage)
                .size(pageSize)
                .build();
        PageQueryPlanScItemListResponse planScItemListResponse = salesPlanService.pageQueryPlanScItemList(request);
        if (planScItemListResponse == null || !planScItemListResponse.getSuccess()) {
            throw new Exception("查询月度计划明细异常");
        }
        Integer total = planScItemListResponse.getTotal();
        int totalPage = total / pageSize;
        if (total % pageSize > 0) {
            totalPage++;
        }
        JSONObject page = new JSONObject();
        page.put("pageSize", pageSize);
        page.put("currentPage", currentPage);
        page.put("totalPage", totalPage);
        result.put("page", page);
        String totalBasicUnit = "";
        List<JSONObject> planLineList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(planScItemListResponse.getResult())) {
            for (Object o : planScItemListResponse.getResult()) {
                JSONObject planLine = JSONObject.parseObject(JSON.toJSONString(o));
                String outerId = planLine.getString("outerId");
                String scItemName = planLine.getString("scItemName");
                int monthCount = planLine.getIntValue("monthCount");
                int taskCount = planLine.getIntValue("taskCount");
                int monthContractCount = planLine.getIntValue("monthContractCount");
                long beforeMonthContractMoney = planLine.getLongValue("beforeMonthContractMoney");
                String basicUnit = planLine.getString("basicUnit");
                if (StringUtils.isNotBlank(basicUnit)) {
                    totalBasicUnit = basicUnit;
                } else {
                    basicUnit = "";
                }
                long beforeMonthMoney = planLine.getLongValue("beforeMonthMoney");
                long beforeTaskMoney = planLine.getLongValue("beforeTaskMoney");
                JSONObject item = new JSONObject();
                item.put("title", scItemName);
                item.put("id", "货品编码: " + outerId);
                if (isPublished) {
                    item.put("planNum", "任务量: " + taskCount + basicUnit);
                    item.put("planAmount", "任务金额: " + formatAmount(beforeTaskMoney));

                } else {
                    item.put("planNum", "计划量: " + monthCount + basicUnit);
                    item.put("planAmount", "计划金额: " + formatAmount(beforeMonthMoney));
                }
                item.put("monthContractCount", "合同量: " + monthContractCount + basicUnit);
                item.put("beforeMonthContractMoney", "合同金额: " + formatAmount(beforeMonthContractMoney));
                planLineList.add(item);
            }

        }
        result.put("planLineList", planLineList);
        result.put("totalBasicUnit", totalBasicUnit);
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        Object requestBody = asyncRequest.getRequestBody();
        if (requestBody == null) {
            return null;
        }
        JSONObject result = new JSONObject();
        try {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(requestBody));
            JSONObject fields = jsonObject.getJSONObject("fields");
            JSONObject page = fields.getJSONObject("page");
            String planId = fields.getString("planId");
            if (page == null || StringUtils.isBlank(planId)) {
                throw new Exception("缺失必要参数:planId");
            }
            Integer pageSize = page.getInteger("pageSize") == null ? 10 : page.getInteger("pageSize");
            Integer currentPage = page.getInteger("currentPage") == null ? 1 : page.getInteger("currentPage");

            handle(result, planId, pageSize, currentPage);
            result.put("planId", planId);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    private String formatAmount(Long money) {
        if (money == null) {
            return "";
        }
        //大于10万，单位为万元
        if (money > 10000000) {
            return new BigDecimal(money).divide(new BigDecimal(1000000), 2, RoundingMode.HALF_DOWN) + "万元";
        }
        return fmtMicrometer(new BigDecimal(money).divide(new BigDecimal(100), 2, RoundingMode.HALF_DOWN).toString()) + "元";
    }

    private String fmtMicrometer(String text) {
        DecimalFormat df = null;
        if (text.indexOf(".") > 0) {
            int index = text.length() - text.indexOf(".") - 1;
            if (index == 0) {
                df = new DecimalFormat("###,##0.");
            } else if (index == 1) {
                df = new DecimalFormat("###,##0.0");
            } else {
                df = new DecimalFormat("###,##0.00");
            }
        } else {
            df = new DecimalFormat("###,##0");
        }
        double number;
        try {
            number = Double.parseDouble(text);
        } catch (Exception e) {
            number = 0.0;
        }
        return df.format(number);
    }
}
